<template>
    <div class="relative w-screen h-screen overflow-hidden bg-black font-sans text-gray-800 leading-relaxed">
        <!-- 下载消息提示 -->
        <Transition
            enter-active-class="transition-all duration-300 ease-out"
            enter-from-class="opacity-0 -translate-y-5"
            enter-to-class="opacity-1 translate-y-0"
            leave-active-class="transition-all duration-300 ease-in"
            leave-from-class="opacity-1 translate-y-0"
            leave-to-class="opacity-0 -translate-y-5"
        >
            <div
                v-if="downloadMessage.show"
                :class="[
          'fixed top-5 left-1/2 -translate-x-1/2 px-6 py-3 rounded-lg text-sm font-medium z-[1000] max-w-[90%] text-center shadow-lg',
          messageTypeClasses[downloadMessage.type]
        ]"
            >
                {{ downloadMessage.text }}
            </div>
        </Transition>

        <!-- 移动端布局 -->
        <div class="block md:hidden relative w-full h-full">
            <div class="relative w-full h-full">
                <img ref="mobileAppImage" src="./images/app.jpeg" alt="SZ坐出租APP" class="absolute top-0 left-0 w-screen h-screen object-fill transition-transform duration-300 ease-in-out z-[1] animate-fade-in" />
                <img
                    src="./images/app_button.svg"
                    alt="下载应用"
                    class="absolute top-[84%] left-1/2 -translate-x-1/2 -translate-y-1/2 cursor-pointer transition-all duration-300 ease-in-out z-10 max-w-[150px] sm:max-w-[180px] md:max-w-[200px] h-auto hover:scale-105 hover:brightness-110 animate-fade-in"
                    style="animation-delay: 0.6s"
                    @click="downloadApk"
                />
            </div>
        </div>

        <!-- PC端布局 -->
        <div class="hidden md:block relative w-full h-full">
            <div class="relative w-full h-full">
                <img ref="desktopAppImage" src="./images/web.jpeg" alt="SZ坐出租WEB版" class="absolute top-0 left-0 w-screen h-screen object-fill transition-transform duration-300 ease-in-out z-[1] scale-100 animate-fade-in" />
                <img
                    src="./images/web_button.svg"
                    alt="立即下载SZ坐出租"
                    class="absolute top-[70%] left-1/4 -translate-x-1/2 -translate-y-1/2 cursor-pointer transition-all duration-300 ease-in-out z-10 max-w-[250px] xl:max-w-[300px] h-auto hover:scale-105 hover:brightness-110 animate-fade-in"
                    style="animation-delay: 0.6s"
                    @click="downloadApk"
                />
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { useRoute } from 'vue-router'

// 类型定义
type MessageType = 'success' | 'warning' | 'error' | 'info'

interface DownloadMessage {
  show: boolean
  text: string
  type: MessageType
}

// 路由信息
const route = useRoute()

// 检查是否为外链模式
const isExternalMode = computed(() => {
  return route.meta?.external === true || 
         route.query?.external === 'true' ||
         route.query?.mode === 'external'
})

// 响应式数据
const mobileAppImage = ref<HTMLImageElement>()
const desktopAppImage = ref<HTMLImageElement>()
const lastDownloadTime = ref(0)
const THROTTLE_DELAY = 5000 // 5秒节流

const downloadMessage = reactive<DownloadMessage>({
  show: false,
  text: '',
  type: 'info'
})

// 消息类型样式映射
const messageTypeClasses = {
  success: 'bg-green-100 text-green-800 border border-green-200',
  warning: 'bg-yellow-100 text-yellow-800 border border-yellow-200',
  error: 'bg-red-100 text-red-800 border border-red-200',
  info: 'bg-blue-100 text-blue-800 border border-blue-200'
}

// 显示下载消息提示
const showDownloadMessage = (message: string, type: MessageType = 'info') => {
  downloadMessage.show = false
  nextTick(() => {
    downloadMessage.text = message
    downloadMessage.type = type
    downloadMessage.show = true

    // 3秒后自动隐藏
    setTimeout(() => {
      downloadMessage.show = false
    }, 3000)
  })
}

// 下载APK功能
const downloadApk = () => {
  const currentTime = Date.now()

  // 检查节流时间
  if (currentTime - lastDownloadTime.value < THROTTLE_DELAY) {
    const remainingTime = Math.ceil((THROTTLE_DELAY - (currentTime - lastDownloadTime.value)) / 1000)
    showDownloadMessage(`请等待 ${remainingTime} 秒后再次下载`, 'warning')
    return
  }

  // 检测设备类型
  const userAgent = navigator.userAgent.toLowerCase()
  const isAndroid = userAgent.includes('android')
  const isMobile = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent)

  // 只允许安卓和PC端下载
  if (!isAndroid && isMobile) {
    showDownloadMessage('此应用仅支持安卓系统和PC端下载', 'error')
    return
  }

  // 更新最后下载时间
  lastDownloadTime.value = currentTime

  // 创建下载链接
  const apkUrl = './assets/__UNI__B062073_0918143041.apk'

  // 创建隐藏的下载链接
  const downloadLink = document.createElement('a')
  downloadLink.href = apkUrl
  downloadLink.download = 'rm1.5.2-2025.8.4.apk'
  downloadLink.style.display = 'none'

  // 添加到页面并触发下载
  document.body.appendChild(downloadLink)
  downloadLink.click()
  document.body.removeChild(downloadLink)

  // 显示下载提示
  showDownloadMessage('开始下载 APK 文件...', 'success')

  // 统计下载事件
  trackDownloadClick('android-apk')
}

// 统计下载点击事件
const trackDownloadClick = (platform: string) => {
  // 这里可以添加统计逻辑
  console.log(`Download clicked for platform: ${platform}`)
}

// 智能图片适配功能
const optimizeImageDisplay = () => {
  const images = [mobileAppImage.value, desktopAppImage.value].filter(Boolean) as HTMLImageElement[]

  images.forEach(img => {
    const handleImageLoad = () => {
      const imgAspectRatio = img.naturalWidth / img.naturalHeight
      const containerAspectRatio = window.innerWidth / window.innerHeight

      // 根据图片和容器的宽高比智能选择显示方式
      if (Math.abs(imgAspectRatio - containerAspectRatio) < 0.1) {
        // 宽高比接近，使用 cover
        img.style.objectFit = 'cover'
        img.style.objectPosition = 'center center'
      } else if (imgAspectRatio > containerAspectRatio * 1.2) {
        // 图片太宽，使用 contain 并居中
        img.style.objectFit = 'contain'
        img.style.objectPosition = 'center center'
        img.style.background = '#000'
      } else if (imgAspectRatio < containerAspectRatio * 0.8) {
        // 图片太高，使用 cover 并调整位置
        img.style.objectFit = 'cover'
        img.style.objectPosition = 'center top'
      } else {
        // 默认使用 cover
        img.style.objectFit = 'cover'
        img.style.objectPosition = 'center center'
      }
    }

    img.onload = handleImageLoad

    // 如果图片已经加载完成
    if (img.complete) {
      handleImageLoad()
    }
  })
}

// 窗口大小改变时重新优化
const handleResize = () => {
  optimizeImageDisplay()
}

// 检查APK文件可用性
const checkApkAvailability = async () => {
  const apkUrl = './assets/rm1.5.2-2025.8.4.apk'

  try {
    const response = await fetch(apkUrl, { method: 'HEAD' })
    if (!response.ok) {
      console.warn('APK文件可能不存在或无法访问')
    }
  } catch (error) {
    console.warn('无法检查APK文件状态:', error)
  }
}

// 生命周期钩子
onMounted(async () => {
  // 等待DOM更新
  await nextTick()

  // 初始化图片优化
  optimizeImageDisplay()

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)

  // 检查APK文件是否存在
  checkApkAvailability()
})

onUnmounted(() => {
  // 清理事件监听器
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
/* 自定义动画延迟 */
.animate-fade-in {
  animation: fadeInUp 0.8s ease-out;
}

/* 确保全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  height: 100%;
  overflow: hidden;
}

/* 字体优化 */
body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
}
</style>
